<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
	<link href="style.css" rel="stylesheet" type="text/css" />
	<script src="jquery-1.8.1.min.js"></script>
	<title>RouletteKut</title>
	
	<script>
		$(document).ready(function(){
			loadBuildings();
			
			$('#addbutton').click(function() {
	 			var oName = $('#officialnamefield').val();
	 			var nName = $('#nicknamefield').val();
	 			var jsonObject = new Object();
	 			jsonObject['official-name'] = oName;
	 			jsonObject['nick-name'] = nName;
	 			
	 			var jsonString = JSON.stringify(jsonObject);
	 			
	 			$.ajax({
	        			type: 'POST',
	        			url: 'rest/buildings',
	        			dataType: 'json',
	        			contentType: 'application/json; charset=utf-8',
	        			data: jsonString,
	        			success: function (result) {
	        				loadBuildings();
	        			},
	        			error: function(result, ajaxOptions, thrownError) {
	        				alert("Errormessage: " + result.status);
	        				alert(thrownError);
	        			}
	    			});
	 		});
 		});
 		
 		function loadBuildings() {
 			$('#buildinglist').empty();
 			$.getJSON('http://localhost:8080/Demo2/rest/buildings', function(data) {
 				$('#buildinglist').append("<tr><th>Official name</th><th>Nickname</th></tr>");
 				var buildingsObj = data.building;
 				$.each(buildingsObj, function(key, buildingObj) {
 					var oName = buildingObj['official-name'];
 					var nName = buildingObj['nick-name'];
 					var id = buildingObj['@id'];
 					
 					if (nName==undefined) {
 						nName = "Niet bekend";
 					}
 					var code = "<tr onClick=\"openBuilding(" + id + ")\"><td>" + oName + "</td><td>" + nName + "</td></tr>";
 					$('#buildinglist').append(code);
 				});
 			});
 		}
 		
 		function openBuilding(id) {
 			window.location = "building.html?id=" + id;
 		}
	</script>
</head>
<body>
	<div id="wrap">
		<header>
			<div>Building Administration</div>
		</header>
		<article>
			<form>
				Official name
				<input type="text" id="officialnamefield"/>
				Nick name
				<input type="text" id="nicknamefield"/>
				<button id="addbutton">Voeg toe</button>
			</form>
			
			<table id="buildinglist">
			</table>
		</article>
	</div>
</body>
</html>